<template>
  <div class="snews">
    <span>最新动态</span>
    <div class="newsList" @mouseover="mouseOver" @mouseout="mouseOut">
      <ul id="con1" :class="{ anim: animate == true }">
        <li v-for="d in state.items" @click="details" :key="d.ID" class="newsItem">
          <span class="ell">【{{ d.department }}】{{ d.name }}</span>
          <i>{{ d.release_time }}</i>
        </li>
      </ul>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, inject, onUnmounted } from "vue";
import { useRouter } from "vue-router";

const http = inject("ajax");
const loginState = inject("loginState");
const route = useRouter();

onMounted(() => {
  getNewsData();
});

const animate = ref(false);
let timer = null; //定时器
let state = reactive({
  items: [
    { department: "加载中...", id: 1 },
    // { department: "新闻1新闻1新闻1新闻1新闻1新闻1新闻1新闻1新闻1新闻1新闻1新闻1新闻1新闻1新闻1新闻1新闻1新闻1新闻1新闻1新闻1新闻1新闻1新闻1新闻1", id: 1 },
    // { department: "新闻2", id: 2 },
    // { department: "新闻3", id: 3 },
  ],
});
function settimer() {
  timer = setInterval(function () {
    scroll();
  }, 2000);
}
const scroll = () => {
  // console.log("执行");

  animate.value = true; // 因为在消息向上滚动的时候需要添加css3过渡动画，所以这里需要设置true
  setTimeout(() => {
    //  这里直接使用了es6的箭头函数，省去了处理this指向偏移问题，代码也比之前简化了很多
    state.items.push(state.items[0]); // 将数组的第一个元素添加到数组的末尾
    state.items.shift(); //删除数组的第一个元素
    animate.value = false; // margin-top 为0 的时候取消过渡动画，实现无缝滚动
  }, 1000);
};
const getNewsData = () => {
  http("/iaiqsmde9fea569965ed56ab98ea0501752fe631902841e/getNewDT", {}, "GET")
    .then(res => {
      if (res.code == 0) {
        state.items = res.data;
        settimer(); //执行定时器方法
      }
    })
    .catch(err => {
      console.log(err.message || "数据异常");
    });
};
const mouseOver = () => {
  // console.log("鼠标悬停");
  clearInterval(timer);
};
const mouseOut = () => {
  // console.log("鼠标移出");
  settimer(); //执行定时器方法
};
onUnmounted(() => {
  clearInterval(timer); //销毁
  timer = null;
});
const details = () => {
  loginState().then(() => {
    route.push({ path: "/DataDirectory" });
  });
};
</script>
